package com.mu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mu.common.Constants;
import com.mu.common.Result;
import com.mu.controller.dto.UserDTO;
import com.mu.entity.Record;
import com.mu.entity.User;
import com.mu.exception.ServiceException;
import com.mu.mapper.UserMapper;
import com.mu.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mu.token.JwtToken;
import com.mu.utils.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mu
 * @since 2022-10-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    public String jwt;

    @Override
    public User findOneByAccount(String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",account);
        User one ;
        try {
            one = getOne(queryWrapper);//从数据库查询用户信息
            //数据库查询，可以视为系统异常
        } catch (Exception e) {
            log.error(String.valueOf(e));
            throw new ServiceException(Constants.CODE_500,"系统错误");//如果有多条数据，返回false
        }
        return one;
    }

    @Override
    public Result login(UserDTO userDTO) {
        if (userDTO.getPassword() == null || userDTO.getAccount() == null) {
            return Result.error(Constants.CODE_500,"用户名或密码错误");
        }
        Subject subject = SecurityUtils.getSubject();
        jwt = JwtUtil.createJWT(userDTO.getAccount(),"back","user",1000*60*30);
        JwtToken jwtToken = new JwtToken(jwt,userDTO.getPassword());
        try{
            subject.login(jwtToken);
        }catch (UnknownAccountException e){
            return  Result.error(Constants.CODE_401,"账号不存在");
        }catch (IncorrectCredentialsException e){
            return  Result.error(Constants.CODE_401,"密码错误");
        }

        User backUser = findOneByAccount(userDTO.getAccount());
        backUser.setPassword(null);
        Map<String,Object> map = new HashMap<>();
        map.put("user",backUser);
        map.put("token",jwt);
        return new Result(Constants.CODE_200,"登录成功",map);
    }

    @Override
    public String getRoleByAccount(String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        User findOne = getOne(queryWrapper);
        if (findOne != null) {
            return findOne.getRole();
        } else {
            return null;
        }
    }
}
